let util = {

}
util.fileFormat = ['jpg', 'jpeg', 'png', 'doc', 'docx', 'xlsx', 'xls', 'pdf', 'ppt', 'pptx', 'txt', 'gif']
util.acceptFormat = 'image/gif,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,text/plain'
util.maxFileSize = 52428800

util.createAreaArr = function (districtCode) {
    // 440103000000
    // 232701000000
  if (!districtCode) return null
  let tempArr = [districtCode + '']
  let temp = districtCode / 100000000
  if (Math.floor(temp) != temp) { tempArr.push(Math.floor(temp) + '00000000') }

  let top = Math.floor(districtCode / 10000000000)
  tempArr.push(top + '0000000000')
  return tempArr.reverse()
}

/*
验证是否int
 */
util.validateInt = (rule, value, callback) => {
  if (value === undefined || value.length === 0) {
    callback(new Error('必须填入数字'))
  } else {
    var num = Number(value)
    var dotIndex = -1
    try {
      dotIndex = value.indexOf('.')
    } catch (e) {}

    if (num >= 0) {
      if (num > 99999) { callback(new Error('超出最大值99,999')) } else if (dotIndex >= 0) {
        callback(new Error('必须填入整数'))
      } else { callback() }
    } else {
      callback(new Error('请填写正确的数字'))
    }
  }
}

util.toTreeData = function (data, attributes, lv) {
  let resData = data
  let tree = []
  var levelNum = 1
  for (let i = 0; i < resData.length; i++) {
    if (resData[i][attributes.parentId] === attributes.rootId || attributes.rootId === false) {
      resData[i].value = resData[i].id = resData[i][attributes.id]
      resData[i].label = resData[i].title = resData[i][attributes.name]
      resData[i].children = []
      tree.push(resData[i])
      resData.splice(i, 1)
      i--
    }
  }
  run(tree, levelNum)
  function run (parentArr, level) {
    if (resData.length !== 0) {
      for (let i = 0; i < parentArr.length; i++) {
        for (let j = 0; j < resData.length; j++) {
          if (parentArr[i].id == resData[j][attributes.parentId]) {
            resData[j].id = resData[j][attributes.id]
            resData[j].value = resData[j][attributes.id]
            resData[j].title = resData[j][attributes.name]
            resData[j].label = resData[j][attributes.name]
            resData[j].children = []
            parentArr[i].children.push(resData[j])
            resData.splice(j, 1)
            j--
          }
        }
        if (!lv || lv > level) { run(parentArr[i].children, level + 1) }
      }
    }
  }

  return tree
}

util.buildTree = function (list, parentKey, idKey) {
  // console.log(list)
  let temp = {}
  let tree = []
  for (let i in list) {
    temp[list[i][idKey]] = list[i]
  }
  // console.log(temp)
  for (let j in temp) {
    if (temp[j][parentKey]) {
      if (!temp[temp[j][parentKey]]) {
        tree.push(temp[j])
      } else {
        if (!temp[temp[j][parentKey]].children) {
          temp[temp[j][parentKey]].children = []
        }
        temp[temp[j][parentKey]].children.push(temp[j])
      }
    } else {
      tree.push(temp[j])
    }
  }
  return tree
}

util.getLangFromStruct = function (labelStruct, lang) {
  var struct = {'Default': ''}
  try {
    struct = JSON.parse(labelStruct)
  } catch (e) {
    struct = {'Default': ''}
  }
  var label = ''
  if (!lang) { lang = 'Default' }

  if (struct[lang]) { label = struct[lang] }
  return label
}

/**
 * 检测字符在是否存在表情
 *
 */
util.hasEmoji = function (substring) {
  let regRule = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g
  if (substring.match(regRule)) {
    substring = substring.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, '')
    return true
  }

  for (var i = 0; i < substring.length; i++) {
    var hs = substring.charCodeAt(i)
    if (hs >= 0xd800 && hs <= 0xdbff) {
      if (substring.length > 1) {
        var ls = substring.charCodeAt(i + 1)
        var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000
        if (uc >= 0x1d000 && uc <= 0x1f77f) {
          return true
        }
      }
    } else if (substring.length > 1) {
      var ls = substring.charCodeAt(i + 1)
      if (ls == 0x20e3) {
        return true
      }
    } else {
      if (hs >= 0x2100 && hs <= 0x27ff) {
        return true
      } else if (hs >= 0x2B05 && hs <= 0x2b07) {
        return true
      } else if (hs >= 0x2934 && hs <= 0x2935) {
        return true
      } else if (hs >= 0x3297 && hs <= 0x3299) {
        return true
      } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 ||
        hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b ||
        hs == 0x2b50) {
        return true
      }
    }
  }
  return false
}

util.getQueryString = function (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

util.getHashQuery = function (val) {
  const w = location.hash.indexOf('?')
  const query = location.hash.substring(w + 1)

  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=')
    if (pair[0] === val) { return pair[1] }
  }
  return (false)
}

util.getObjInArr = function(arr,key,value) {
  for(var i in arr)
  {
    if(arr[i][key] === value)
      return arr[i]
  }
  return null;
}

// 合并两个对象相同的值
util.assignSame = function (obj, concatObj) {
  for (let key in obj) {
    if (obj[key] != null && concatObj[key] != null) {
      obj[key] = concatObj[key]
    }
  }
  return obj
}

Date.prototype.Format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
  return fmt
}

// 读取cookies
util.getCookie = (name) => {
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  const arr = document.cookie.match(reg)
  if (arr) {
    return unescape(arr[2])
  } else {
    return null
  }
}

// 把流对象分装文件输出下载
util.blobDownload = (res, options = {}) => {
  // 匹配到excel的文件名
  const filename = decodeURI(res.headers['content-disposition'].match(/filename=(.*)/)[1]) || '未命名文件'
  const blob = new Blob([res.data], options)
  if (navigator.appVersion.toString().indexOf('.NET') > 0) {
    window.navigator.msSaveBlob(blob, filename)
  } else {
    const downloadElement = document.createElement('a')
    const href = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadElement.href = href
    downloadElement.download = filename // 下载后文件名
    // downloadElement.download = filename
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  }
}

// 获取当前树节点的父级
util.getTreeParent = (data2, nodeId2, key) => {
  let arrRes = []
  if (data2.length == 0) {
    if (nodeId2) {
      arrRes.unshift(data2)
    }
    return arrRes
  }
  const rev = (data, nodeId) => {
    for (let i = 0, length = data.length; i < length; i++) {
      let node = data[i]
      if (node[key] == nodeId) {
        arrRes.unshift(node)
        rev(data2, node.parent_id)
        break
      } else {
        if (node.children) {
          rev(node.children, nodeId)
        }
      }
    }
    return arrRes
  }
  arrRes = rev(data2, nodeId2)
  return arrRes
}

util.formatMoneyInt = val => {
  if(!val) return "0";
  val = val.toString().replace(/\$|\,/g,'');
  if(isNaN(val)) {
    val = "0";
  }
  let sign = (val == (val = Math.abs(val)));
  val = Math.floor(val*100+0.50000000001);
  val = Math.floor(val/100).toString();
  for (var i = 0; i < Math.floor((val.length-(1+i))/3); i++) {
    val = val.substring(0,val.length-(4*i+3))+',' + val.substring(val.length-(4*i+3));
  }
  return (((sign)?'':'-') + val);
}

util.formatMoney = function(val) {
  if (!val) return "0";
  val = val.toString().replace(/\$|\,/g,'');
  if(isNaN(val)) {
    val = "0";
  }
  let sign = (val == (val = Math.abs(val)));
  val = Math.floor(val*100+0.50000000001);
  let cents = val%100;
  val = Math.floor(val/100).toString();
  if(cents<10) {
    cents = "0" + cents
  }
  for (var i = 0; i < Math.floor((val.length-(1+i))/3); i++) {
    val = val.substring(0,val.length-(4*i+3))+',' + val.substring(val.length-(4*i+3));
  }

  return (((sign)?'':'-') + val + '.' + cents);
}

// val 为时间戳
util.formateDate = function(timestamp, type) {
  var date = new Date(timestamp)
  var Y = date.getFullYear();
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
  var D = date.getDate() < 10 ? '0'+ date.getDate() : date.getDate();
  var h = date.getHours() < 10 ? '0'+date.getHours(): date.getHours();
  var m = date.getMinutes() < 10 ? '0'+date.getMinutes(): date.getMinutes();
  var s = date.getSeconds() < 10 ? '0'+date.getSeconds(): date.getSeconds();
  if (type = 'date') {
    return Y + '.' + M + '.' + D
  } else {
    return Y+'.'+M+'.'+D + ' ' + h + ':' + m + ':' + s
  }
}

util.getByteLen = function (val) {
  var len = 0
  for (var i = 0; i < val.length; i++) {
    var length = val.charCodeAt(i)
    if (length >= 0 && length <= 128) {
      len += 1
    } else {
      len += 2
    }
  }
  return len
}

/**
 * 获取链接参数
 * @param {String} name - 参数名
 */
util.getUrlParam = name => {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  if (window.location.href.indexOf('?') == -1) return
  var r = window.location.hash.split('?')[1].match(reg)
  if(r !== null){
    return unescape(r[2])
  }
  return null
}

// 节流
util._throttle = function (fn, delay = 5) {
  let lastTime, timer
  return function () {
    let _this = this
    let args = arguments
    let nowTime = Date.now()
    if (lastTime && nowTime - lastTime < delay) {
      if (timer) clearTimeout(timer)
      timer = setTimeout(function () {
        lastTime = nowTime
        fn.apply(_this, args)
      }, delay)
    } else {
      lastTime = nowTime
      fn.apply(_this, args)
    }
  }
}

util.handleDocType = function (fileType) {
  let docType = ''
  let fileTypesDoc = ['doc', 'docm', 'docx', 'dot', 'dotm', 'dotx', 'epub', 'fodt', 'htm', 'html', 'mht', 'odt', 'ott']
  let fileTypesCsv = ['csv', 'fods', 'ods', 'ots', 'xls', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx']
  let fileTypesPPt = ['fodp', 'odp', 'otp', 'pot', 'potm', 'potx', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx']
  if (fileTypesDoc.includes(fileType)) {
    docType = 'word'
  }
  if (fileTypesCsv.includes(fileType)) {
    docType = 'spreadsheet'
  }
  if (fileTypesPPt.includes(fileType)) {
    docType = 'presentation'
  }
  return docType
}

export function formatNumber(num) {
  let reg = /(?=(\B)(\d{3})+$)/g;
  return num.toString().replace(reg, ',');
}

export default util
